package com.hepinghospital.user.ui.activity.userinfo;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.eventbus.UpdateFamilyEvent;
import com.hepinghospital.user.ui.dialog.AreaDialogFragment;
import com.hepinghospital.user.ui.dialog.ConfirmDialog;
import com.hepinghospital.user.ui.widget.CustomPopWindow;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.DicResponse;
import com.rest.response.MyFamilyListResponse;
import com.rest.response.MyFamilyResponse;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import jz.joyoung.robot.util.AES128;
import jz.joyoung.robot.util.MatchUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.ValidateUtil;

/**
 * 添加成员/修改成员信息
 *
 * @time 2021/2/26 15:51
 */

public class AddMyFamilyActivity extends BaseActivity {
    @BindView(R.id.edt_name)
    EditText edt_name;
    @BindView(R.id.edt_id_card)
    EditText edt_id_card;
    @BindView(R.id.edt_area)
    TextView edt_area;
    @BindView(R.id.edt_area_detail)
    EditText edt_area_detail;
    @BindView(R.id.edt_phone)
    EditText edt_phone;
    @BindView(R.id.edt_relation)
    TextView edt_relation;
    @BindView(R.id.btn_confirm)
    TextView btn_confirm;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    @BindView(R.id.btn_delete)
    ImageView btnDelete;

    private AreaDialogFragment mAreaDialogFragment;
    MyFamilyListResponse myFamily;
    String ids;
    String currentRaltion = "";
    MyFamilyResponse mFamilyResponse;

    @Override
    protected void initViews() {
        tvTitle.setText("添加就诊人");
        if (myFamily != null) {
            edt_name.setEnabled(false);
            edt_id_card.setEnabled(false);
            edt_area_detail.setEnabled(false);
            edt_area.setEnabled(false);
            edt_phone.setEnabled(false);
//            edt_relation.setEnabled(false);
            btnDelete.setVisibility(View.VISIBLE);
            tvTitle.setText("编辑");
            btn_confirm.setText("保 存");
        }
    }

    @Override
    protected void initData() {
        myFamily = (MyFamilyListResponse) getIntent().getSerializableExtra(UIConstants.OBJ_MyFamilyListResponse);
        if (myFamily != null) {
            getPatientDetail();
        }
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        if (validate()) {
            addFamily();
        }
    }

    @OnClick(R.id.btn_delete)
    void btn_delete() {
        if (myFamily != null) {
            showConfirmDialog();
        }
    }

    private void showConfirmDialog() {
        ConfirmDialog confirmDialog = ConfirmDialog.newInstance("删除后无法恢复\n" +
                "是否删除该成员信息？","");
        confirmDialog.show(getSupportFragmentManager(), "ConfirmDialog");
        confirmDialog.setmListener(new ConfirmDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                delFamily();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private boolean validate() {
        if (TextUtils.isEmpty(edt_name.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请输入姓名");
            return false;
        }
        if (edt_id_card.getText().toString().trim().length() != 18 || !MatchUtil.checkIDCard(edt_id_card.getText().toString().trim(), AddMyFamilyActivity.this)) {
            ToastUtil.showToast(mContext, "身份证有误");
            return false;
        }
        if (TextUtils.isEmpty(edt_area.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请选择地区");
            return false;
        }
        if (TextUtils.isEmpty(edt_area_detail.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请填写详细地址");
            return false;
        }
        if (edt_phone.getText().toString().trim().length() != 11 || !ValidateUtil.checkMobilePhoneNum(edt_phone.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "手机号格式不正确");
            return false;
        }
        return true;
    }

    @OnClick(R.id.edt_area)
    void edt_area() {
        showAreaDialog();
    }

    @OnClick(R.id.edt_relation)
    void edt_relation() {
        showPopListView(edt_relation);
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_add_my_family;
    }

    private void getPatientDetail() {
        RestProxy.getInstance().getPatientDetail(myFamily.id, new BaseObserver<MyFamilyResponse>() {
            @Override
            public void onSuccess(MyFamilyResponse myFamilyResponse) {
                mFamilyResponse = myFamilyResponse;
                edt_name.setText(myFamilyResponse.name);
                edt_id_card.setText(myFamilyResponse.idcard);
                edt_area_detail.setText(myFamilyResponse.addr);
                edt_phone.setText(myFamilyResponse.phone);
                edt_relation.setText(myFamilyResponse.relationName);
                edt_area.setText(myFamilyResponse.area);
                checkBox.setChecked(myFamilyResponse.isDefault == 1);
            }
        });
    }


    private void addFamily() {
        try {
            String province, city, region;
            if (mFamilyResponse != null) {
                province = mFamilyResponse.province;
                city = mFamilyResponse.city;
                region = mFamilyResponse.region;
            } else {
                String[] split = ids.split(",");
                province = split[0];
                city = split[1];
                region = split[2];
            }
            RestProxy.getInstance().addFamily(edt_name.getText().toString(), edt_id_card.getText().toString(),
                    AES128.encryptStringAES(edt_phone.getText().toString(), "7t3e506jaa10xbd4"),
                    edt_area_detail.getText().toString(), currentRaltion, "0", province, city, region, new BaseObserver<String>() {
                        @Override
                        public void onSuccess(String s) {
                            finish();
                            EventBus.getDefault().post(new UpdateFamilyEvent());
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            ToastUtil.onError(AddMyFamilyActivity.this, e);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void delFamily() {
        RestProxy.getInstance().delFamily(myFamily.id, new BaseObserver<String>() {
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(AddMyFamilyActivity.this, e);
            }

            @Override
            public void onSuccess(String result) {
                EventBus.getDefault().post(new UpdateFamilyEvent());
                finish();
            }
        });
    }


    private void showAreaDialog() {
        if (mAreaDialogFragment == null) {
            mAreaDialogFragment = AreaDialogFragment.newInstance();
            mAreaDialogFragment.setmListener((ids, address) -> {
                AddMyFamilyActivity.this.ids = ids;
                edt_area.setText(address);
            });
            mAreaDialogFragment.show(getSupportFragmentManager(), "mAreaDialogFragment");
        } else if (!mAreaDialogFragment.isAdded() && !mAreaDialogFragment.isShowing()) {
            mAreaDialogFragment.show(getSupportFragmentManager(), "mAreaDialogFragment");
        }
    }


    private CustomPopWindow mPopWindow;
    AddMedicineAdapter adapter;
    List<DicResponse> list = new ArrayList<>();


    private void showPopListView(View view) {
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(AddMyFamilyActivity.this).inflate(R.layout.pop_window, null);
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(AddMyFamilyActivity.this));
        adapter = new AddMedicineAdapter();
        recyclerView.setAdapter(adapter);
        list.clear();
        list.add(new DicResponse("本人", "1"));
        list.add(new DicResponse("配偶", "2"));
        list.add(new DicResponse("父母", "3"));
        list.add(new DicResponse("子女", "4"));
        list.add(new DicResponse("其他", "5"));

        //创建并显示popWindow
        mPopWindow = new CustomPopWindow.PopupWindowBuilder(AddMyFamilyActivity.this)
                .setView(contentView)
                .setTouchable(true)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .create()
                .showAsDropDown(view);
    }

    class AddMedicineAdapter extends RecyclerView.Adapter<AddMedicineAdapter.Holder> {


        AddMedicineAdapter() {
        }

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(AddMyFamilyActivity.this).inflate(R.layout.item_textview, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                edt_relation.setText(list.get(position).name);
                currentRaltion = list.get(position).code;
                mPopWindow.dissmiss();
            });
            holder.tv_name.setText(list.get(position).name);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.text);
            }
        }
    }
}
